import 'package:flutter/material.dart';

import 'my_change_notifier.dart';
import 'my_provider.dart';

//该类用于将数据提供者MyProvider和要显示的UI绑定到一起
//author:liuhaichao
class ProviderCreator<T extends MyChangeNotifier> extends StatefulWidget {
  const ProviderCreator({
    Key? key,
    required this.viewModel,
    required this.child,
  }) : super(key: key);
  final T viewModel;
  final Widget child;

  //定义一个便捷方法，方便子树中的widget获取共享数据
  static T? of<T extends MyChangeNotifier>(BuildContext context, {bool dependOn = true}) {
    if (dependOn) {
      return context.dependOnInheritedWidgetOfExactType<MyProvider<T>>()?.viewModel;
    } else {
      return (context.getElementForInheritedWidgetOfExactType<MyProvider<T>>()?.widget as MyProvider<T>).viewModel;
    }
  }

  @override
  State<ProviderCreator> createState() => _ProviderCreatorState<T>();
}

class _ProviderCreatorState<T extends MyChangeNotifier> extends State<ProviderCreator<T>> {
  void update() {
    setState(() {});
  }

  @override
  void initState() {
    widget.viewModel.addListener(update);
    super.initState();
  }

  @override
  void dispose() {
    widget.viewModel.removeListener(update);
    super.dispose();
  }

  @override
  void didUpdateWidget(ProviderCreator<T> oldWidget) {
    //当Provider更新时，如果新旧数据不"=="，则解绑旧数据监听，同时添加新数据监听
    if (widget.viewModel.shouldNotify(oldWidget.viewModel)) {
      oldWidget.viewModel.removeListener(update);
      widget.viewModel.addListener(update);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("_ProviderCreatorState");
    return MyProvider<T>(
      viewModel: widget.viewModel,
      child: widget.child,
    );
  }
}
